package rwlivbk.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import rwlivbk.constants.LiveConstants;
import rwlivbk.service.ChatService;

@Configuration
@Slf4j
@CrossOrigin
public class RabbitMQConfig {

    @Autowired
    private ConnectionFactory connectionFactory;
    @Autowired
    private ChatService chatService;

    @Bean
    public Queue stompQueue() {
        return new Queue(LiveConstants.STOMP_QUEUE, true);
    }

    @Bean
    public Queue viewerQueue() {
        return new Queue(LiveConstants.VIEWER_QUEUE, true);
    }

    @Bean
    TopicExchange stompTopicExchange() {
        return new TopicExchange(LiveConstants.STOMP_EXCHANGE, true, false);
    }

    @Bean
    TopicExchange viewerTopicExchange() {
        return new TopicExchange(LiveConstants.VIEWER_TOPIC_EXCHANGE, true, false);
    }

    @Bean
    Binding stompBinding() {
        return BindingBuilder.bind(stompQueue()).to(stompTopicExchange()).with(LiveConstants.STOMP_ROUTE_KEY);
    }

    @Bean
    Binding viewerBinding() {
        return BindingBuilder.bind(viewerQueue()).to(viewerTopicExchange()).with("");
    }

    @Bean
    SimpleMessageListenerContainer messageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(stompQueue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(100);
        container.setConcurrentConsumers(10);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener((ChannelAwareMessageListener) (message, channel) -> {
            byte[] body = message.getBody();
            String msg = new String(body);
            log.info("RabbitMQ received message: {}", msg);
            boolean sendToWebsocket = chatService.sendMsg(msg);
            if (sendToWebsocket) {
                log.info("Message processed successfully and pushed to websocket!");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            }
        });
        return container;
    }
}
